import redis
from django.db import DatabaseError
from django.http import JsonResponse
from QQLoginTool.QQtool import OAuthQQ
from django.views import View
from django.contrib.auth import login
import json
import re
from django_redis import get_redis_connection
from utils.views import check_access_token
from apps.oauth.models import OAuthQQUser
from jinhuan_mall import settings
from apps.users.models import User


class QQLogin(View):
    def get(self,request):
        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state='next'
        )
        qq_url_get = qq.get_qq_url()
        return JsonResponse({'code':0,'errmsg':'OK','login_url':qq_url_get})


class OauthUserView(View):
    def get(self, request):
        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state='next'
        )
        code = request.GET.get('code')
        token = OAuthQQ.get_access_token(code)
        openid = OAuthQQ.get_open_id(token)


        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            response = JsonResponse({'code':300,'access_id':'access_id'})
            return response
        else:
            login(request,qquser.user)
            response = JsonResponse({'code':0, 'errmsg':'ok'})
            response.set_cookie('username',qquser.user.username)
            return response

    def post(self,request):
        """美多商城用户绑定到openid"""
        # 1.接收参数
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')
        sms_code = dict.get('sms_code')
        access_token = dict.get('access_token')
        # 2.校验参数
        # 判断参数是否齐全
        if not all[mobile,password,sms_code,access_token]:
            return JsonResponse({'code':400,'errmsg':'参数不全'})
        # 判断手机号是否合法
        if not re.match('^1[3-9]{9}',mobile):
            return JsonResponse({'code':400,'errmsg':'手机号格式有误'})
        # 判断密码是否合格
        if not re.match('[a-zA-z0-9]{8,20}',password):
            return JsonResponse({'code': 400, 'errmsg': '密码格式有误'})
        # 3.判断短信验证码是否一致
        # 创建 redis 链接对象:
        redis_cli = get_redis_connection('code')
        # 从 redis 中获取 sms_code 值:
        sms_code1 = redis.Redis.get('sms_code')
        # 判断获取出来的有没有:
        if sms_code1 is None:
            return JsonResponse({'code': 400, 'errmsg': '验证码已过期'})
        # 如果有, 则进行判断:
        if sms_code1 != sms_code.decode():
            # 如果不匹配, 则直接返回:
            return JsonResponse({'code': 400, 'errmsg': '输入的验证码有误'})
        # 调用我们自定义的函数, 检验传入的 access_token 是否正确:
        # 错误提示放在 sms_code_errmsg 位置
        openid = check_access_token(access_token)
        if not access_token:
            return JsonResponse({'code': 400, 'errmsg': '缺少openid'})
        # 4.保存注册数据
        # 用户不存在,新建用户
        try:
            user = User.objects.get(mobile = mobile)
        except User.DoesNotExist:
            user = User.objects.create_user(
                username=mobile,
                password=password,
                mobile=mobile
            )
        # 如果用户存在，检查用户密码
        else:
            if not user.check_password(password):
                return JsonResponse({'code':400,'errmsg':'输入的密码不正确'})
        # 5.将用户绑定 openid
        try:
            User.objects.create(openid=openid,
                                user = user)
        except DatabaseError:
            return JsonResponse({'code': 400,
                                      'errmsg': '往数据库添加数据出错'})
        # 6.实现状态保持
        login(request,user)
        # 7.创建响应对象:
        response = JsonResponse({'code':0,'errmsg': 'ok'})
        # 8.登录时用户名写入到 cookie，有效期14天
        response.set_cookie('username',user.username,max_age=3600 * 24 *14)
        # 9.响应
        return response
